#include "Alarm_Task.h"
#include "74HC595.h"
#include "Output.h"
#include "Power_Task.h"
#include "Sensor_Read_Task.h"
#include "W25QXX.h"
#include "modbus.h"

void Alarm_Task(void* pdata) {
    for (;;) {
        OSTimeDly(100);
        uint8_t temp_alarm = 0;
        if (Get_recive_time() == 0 && Sys_Base.para.reset == 0) {   // 正常启动，通讯超时
            Sys_Base.para.reset = 1;
            SPI_Flash_Write((INT8U*) &Sys_Base.para.slave_id, para_data_addr, sizeof(Sys_Base.para));
            SystemReset();
        }
        if (Get_recive_time() == 0 && Sys_Base.para.reset == 1) {   // 重启启动，通讯超时
            Emer.enable = EMER_ENABLE;                              // 应急风机使能
        }
        if (Sys_Base.para.reset == 0) {
            Emer.enable = EMER_DISABLE;   // 应急风机失能
        }
        for (uint8_t i = 0; i < TEMP_NUM_MAX; i++) {   // 高温，低温报警
            if (Get_sensor_temp(i) >= Sys_Base.para.High_temp + Sys_Base.para.target_temp ||
                Get_sensor_temp(i) <= Sys_Base.para.Low_temp + Sys_Base.para.target_temp) {
                temp_alarm = 1;
                break;
            } else {
                temp_alarm = 0;
            }
        }
        Output_Control(0, Emer.enable | (!Get_Power_ac_state()));   // 通讯断开/电源未接入报警
        Output_Control(1, temp_alarm);                              // 高温，低温报警

        if (Emer.enable == EMER_DISABLE) {
            continue;
        }
        for (uint8_t i = 0; i < TEMP_SENSOR_NUM; i++) {
            uint8_t state = 0;
            if (Get_sensor_temp(i) >= Sys_Base.para.target_temp + Sys_Base.para.start_dif[i]) {
                state = STATE_ON;
            } else {
                state = STATE_OFF;
            }
            JDQ_Control(i + 1, state);
        }
    }
}
uint8_t Get_Emer_enable(void) {
    return Emer.enable;
}
// 设置应急风机使能/失能
void Set_emer_enable(uint8_t state) {
    if (state > STATE_ON) {
        return;
    }
    Emer.enable = state;
}
// 通讯正常，状态恢复
void Set_sys_reset(void) {
    if (Sys_Base.para.reset == 1) {
        Sys_Base.para.reset = 0;   // 正常启动
        SPI_Flash_Write((INT8U*) &Sys_Base.para.slave_id, para_data_addr, sizeof(Sys_Base.para));
    }
}
